package com.lcifn.zk.console.controller;

import com.lcifn.zk.console.support.ZkSession;
import com.lcifn.zk.console.support.ZkSessionSupport;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title: IndexController.java<br>
 * Description:  <br>
 * Copyright: Copyright (c) 2020<br>
 *
 * @author lichao
 * @date 2020/6/10 16:02
 */
@RestController
public class IndexController {

    @Autowired
    private ZkSessionSupport zkSessionSupport;

    @RequestMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("index");
    }

    @RequestMapping("/index2")
    public ModelAndView index2() {
        return new ModelAndView("index2");
    }

    /**
     * zk连接测试
     * @param param
     * @return
     */
    @PostMapping("/checkConnect")
    public Map<String, Object> checkConnectZk(@RequestBody Map<String, String> param) {
        String zkAddress = param.get("addr");
        boolean connected = zkSessionSupport.checkConnection(zkAddress);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("connected", connected);
        return retMap;
    }

    /**
     * 创建zk连接配置
     * @param param
     * @return
     */
    @PostMapping("/connect")
    public Map<String, Object> connectZk(@RequestBody Map<String, String> param) {
        String zkAddress = param.get("addr");
        // 创建session
        ZkSession zkSession = zkSessionSupport.buildSession(zkAddress);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("sessionId", zkSession.getSessionId());
        return retMap;
    }

    @PostMapping("/listNode")
    public List<String> listNode(@RequestBody Map<String, String> param) throws Exception {
        String addr = param.get("addr");
        String path = param.get("path");
        ZkSession session = zkSessionSupport.getSession(addr);
        Stat stat = session.statNode(path);
        if (stat != null) {
            List<String> childrenList = session.childNode(path);
            return childrenList;
        }
        return null;
    }

    @PostMapping("/getNodeData")
    public Stat getNodeData(@RequestBody Map<String, String> param) throws Exception {
        String path = param.get("path");
        String sessionId = param.get(ZkSession.SESSION_ID);
        ZkSession session = zkSessionSupport.getSession(sessionId);
        Stat stat = session.statNode(path);
        return stat;
    }
}
